﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using WyUnity.Utility.ExtentionMethods;
using System.Reflection;

namespace WyUnity.Utility
{
    public static class Util
    {
        private const string MD5_Hash_ADDING = "@z%F.!(#|*]}";

        public static string HashString(string str)
        {
            //var md5 = new MD5CryptoServiceProvider();
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var v = sha1.ComputeHash(Encoding.UTF8.GetBytes(str + MD5_Hash_ADDING));
            Contract.Assume(v.Length > 12);
            string t2 = BitConverter.ToString(v);
            t2 = t2.Replace("-", "");
            return t2;
        }


        public readonly static DateTime DbMinDate = new DateTime(1900, 1, 1);
        /// <summary>
        /// 获取新的Guid，用于数据的主键，不要使用Guid.NewGuid方法获取。
        /// 使用本方法获取的主键是有序的，有利于数据库的数据组织，提升效率
        /// </summary>
        public static Guid GenerateGuid()
        {
            var guidArray = Guid.NewGuid().ToByteArray();

            var baseDate = new DateTime(1900, 1, 1);
            var now = DateTime.Now;

            // Get the days and milliseconds which will be used to build 
            //the byte string 
            var days = new TimeSpan(now.Ticks - baseDate.Ticks);
            var msecs = now.TimeOfDay;

            // Convert to a byte array   
            // SQL Server is accurate to 1/300th of a 
            // millisecond so we divide by 3.333333 
            byte[] daysArray = BitConverter.GetBytes(days.Days);
            byte[] msecsArray = BitConverter.GetBytes((long)
(msecs.TotalMilliseconds / 3.333333));

            // Reverse the bytes to match SQL Servers ordering 
            Array.Reverse(daysArray);
            Array.Reverse(msecsArray);

            // Copy the bytes into the guid 
            Array.Copy(daysArray, daysArray.Length - 2, guidArray,
guidArray.Length - 6, 2);
            Array.Copy(msecsArray, msecsArray.Length - 4, guidArray,
guidArray.Length - 4, 4);

            return new Guid(guidArray);
        }
        /// <summary>
        /// 获取应用程序的目录，末尾不带\
        /// </summary>
        /// <returns></returns>
        public static string GetAppFolder()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory;

            if (path.IsNullOrEmpty()) throw new ApplicationException("获取应用程序目录失败");

            if (path.Substring(path.Length - 1) == "\\")
                path = path.Substring(0, path.Length - 1);

            return path;
        }

        public static string GetAppSetting(string name)
        {
            return System.Configuration.ConfigurationManager.AppSettings[name];
        }

        public static string GetConfigConnectionString(string name)
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }
        public static T ConvertType<T>(object value, T defaultValue = default(T))
        {
            return value.TryTo<T>();
        }
        public static object ConvertType(object value, Type distinctType, object defaultValue)
        {
            return value.TryTo(distinctType, defaultValue);
        }

        #region 反射相关
        public static T GetCustomAttribute<T>(this MethodInfo method, bool inherit) where T : Attribute
        {
            var atts = method.GetCustomAttributes(typeof(T), inherit);
            if (atts.Length == 0) return null;
            return atts[0] as T;
        }

        public static T GetCustomAttribute<T>(this PropertyInfo method, bool inherit) where T : Attribute
        {
            var atts = method.GetCustomAttributes(typeof(T), inherit);
            if (atts.Length == 0) return null;
            return atts[0] as T;
        }

        public static T GetCustomAttribute<T>(this Type type, bool inherit) where T : Attribute
        {
            var atts = type.GetCustomAttributes(typeof(T), inherit);
            if (atts.Length == 0) return null;
            return atts[0] as T;
        }
        #endregion

    }
}
